//
//  JXLPictureView.swift
//  MicroBlog
//
//  Created by 贾晓磊 on 16/9/26.
//  Copyright © 2016年 贾晓磊. All rights reserved.
//

import UIKit
import SDWebImage
//  重用标记
private let JXLStatusPictureViewCellIdentifier = "JXLStatusPictureViewCellIdentifier"

//每个配图之间的间距
let itemMargin: CGFloat = 5
//每个配图的宽度
let itemWidth = CGFloat(Int(ScreenWidth - 2 * JXLHomeTableViewCellMargin - 2 * itemMargin) / 3)

//自定义微博首页配图视图
class JXLStatusPictureView: UICollectionView {
    
    var picUrls: [JXLStatusPictureInfo]? {
    //设置配图数据源
        didSet {
            
            //            guard let urls = picUrls else {
            //                return
            //            }
            //
            //            if urls.count > 0 {
            //                //显示配图个数
            //                countLabel.text = "\(picUrls?.count ?? 0)"
            //                //计算size
            //                let size = calculateSize(count: picUrls?.count ?? 0)
            //
            //                //  设置约束大小
            //                self.snp_updateConstraints { (make) in
            //                    make.size.equalTo(size)
            //                }
            //
            //            }
            countLabel.text = "\(picUrls?.count ?? 0)"
            //计算size
            let size = calculateSize(count: picUrls?.count ?? 0)
            
            //  设置约束大小
            self.snp_updateConstraints { (make) in
                make.size.equalTo(size)
            }
            
            self.reloadData()
        }
        
    }
    //显示配图数量的label
    private lazy var countLabel: UILabel = {
        let label = UILabel(fontSize: 20, textColor: UIColor.magenta)
        
        return label
    }()
    
    //重写构造方法
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        //创建布局对象
        let flowLayout = UICollectionViewFlowLayout()
        //设置每个cell的大小
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        //设置cell被迫换行的间距
        flowLayout.minimumLineSpacing = itemMargin
        //设置cell之间的间距
        flowLayout.minimumInteritemSpacing = itemMargin
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //添加并且布局子控件
    private func setupUI() {
        //注册tableViewCell
        register(JXLStatusPictureViewCell.self, forCellWithReuseIdentifier: JXLStatusPictureViewCellIdentifier)
        
        //设置代理
        self.dataSource = self
        
        //添加子控件
        addSubview(countLabel)
        
        //布局子控件
        countLabel.snp_makeConstraints { (make) in
            make.center.equalTo(self)
        }
        
    }
    
    //根据配图张数，计算配图大小
    private func calculateSize(count: Int) -> (CGSize) {
        
        //  判断图片个数是否等于1,如果图片的个数等于1 表示要从缓存中去图片
        if count == 1 {
            
            let url = picUrls!.first!.thumbnail_pic!
            //从缓存中取图片
           let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: url)
            //如果图片不为nil，则说明拿到了想要的图片
            if image != nil {
                //  注意一个问题 , 单张图片的大小 绑定数据时候图片比设置条目的大小要大,那么就会出现警告
            var size = image!.size
                
                //  如果图片的宽度小于指定的大小,那么需要等比计算图片的高度
                //  图片过窄处理 -> 产品处理这个问题
                if size.width < 80 {
                    //指定宽度
                    let scaleWidth: CGFloat = 80
                    let height = CGFloat(Int(scaleWidth / size.width * size.height))
                    
                    let scaleHeight = height > 150 ? 150: height
                    
                    size.width = scaleWidth
                    size.height = scaleHeight
                }
                
                //调整条目大小
                let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
               //调整单张图片条目大小
                flowLayout.itemSize = size
                return size
            }
            
        }
        
        //如果不是单张图片，大小设置成计算好的大小
        //调整条目大小
        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        //调整单张图片条目大小
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        //        //每个配图之间的间距
        //        let itemMargin: CGFloat = 5
        //        //每个配图的宽度
        //        let itemWidth = (ScreenWidth - 2 * JXLHomeTableViewCellMargin - 2 * itemMargin) / 3
        
        //计算列数
        let cols = count > 3 ? 3 : count
        //计算行数
        let rows = (count - 1) / 3 + 1
        
        //计算当前配图的宽度
        let currentWidth = itemWidth * CGFloat(cols) + CGFloat(cols - 1) * itemMargin
        //计算当前配图的高度
        let currentHeight = itemWidth * CGFloat(rows) + CGFloat(rows - 1) * itemMargin
        
        return CGSize(width: currentWidth, height: currentHeight)
    }
}


//UIcollectionViewCell DataSource
extension JXLStatusPictureView: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return  picUrls?.count ?? 0
    }
    
    
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: JXLStatusPictureViewCellIdentifier, for: indexPath) as! JXLStatusPictureViewCell
        
        cell.statusPictureInfo = picUrls![indexPath.row]
        
        return cell
    }
    
    
}

// MARK: 自定义配图cell
class JXLStatusPictureViewCell: UICollectionViewCell {
    
    //设置模型数据
    var statusPictureInfo: JXLStatusPictureInfo? {
        didSet {
            
            if let url = statusPictureInfo?.thumbnail_pic {
                //如果url不为空，就加载数据
                imageView.sd_setImage(with: URL(string: url), placeholderImage: UIImage(named: "timeline_image_placeholder"))
            }
            
        }
    }
    
    //展示配图的imageView
    lazy var imageView: UIImageView = {
        let view = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
       //设置图片填充模式,原比例填充
        view.contentMode = .scaleAspectFill

        //  会有超出范围显示,  剪切多余部分
        view.clipsToBounds = true

        return view
    }()
    
   override init(frame: CGRect) {
        super.init(frame: frame)
    
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //添加并布局子控件
    func setupUI() {
        addSubview(imageView)
        
        //设置约束
        imageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView).offset(UIEdgeInsets.zero)
        }
    }
}
